package com.example.yichuangyun.ui.activity;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;

import com.example.yichuangyun.R;
import com.example.yichuangyun.application.MyApplication;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityLoginBinding;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.StatusModel;
import com.example.yichuangyun.model.UserInfoModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.sharedpreference.SPUtil;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 登录
 */
public class LoginActivity extends BaseActivity<ActivityLoginBinding, BaseViewModel> implements TextWatcher {

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        binding.etInputPhone.setText(SPUtil.getString(Constant.phoneNum, ""));
    }

    @Override
    protected void initClick() {
        binding.cdtCountdown.setOnClickListener(v -> {
            if (TextUtils.isEmpty(binding.etInputPhone.getText().toString())) {
                ToastHelper.show(getString(R.string.hint_input_tel));
                return;
            }
            sendCode();
        });
        binding.btnConfirm.setOnClickListener(v -> {
            CommonUtil.closeKeyboard(this);
            login();
        });
        binding.etInputPhone.addTextChangedListener(this);
        binding.etInputCode.addTextChangedListener(this);
    }

    /**
     * 获取验证码
     */
    private void sendCode() {
        showLoadingDialog();
        String phoneNum = binding.etInputPhone.getText().toString().trim();
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put("phone", phoneNum);
            requestDate.put("action", 5);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().sendCode(requestBody), new MyObserver<StatusModel>() {
            @Override
            protected void onSuccess(StatusModel statusModel) {
                if (statusModel != null) {
                    if (statusModel.getStatus() == 200) {
                        binding.cdtCountdown.startCountDown(context, 60, getString(R.string.send_code_again), "s");
                        ToastHelper.show(getString(R.string.code_has_been_sent));
                    } else {
                        ToastHelper.show(statusModel.getMessage());
                    }
                } else {
                    ToastHelper.show(getString(R.string.send_fail));
                }
                dismissLoadingDialog();
            }

            @Override
            protected void onFail(Throwable e) {
                ToastHelper.show(e.getMessage());
                dismissLoadingDialog();
            }
        });
    }

    /**
     * 登录
     */
    private void login() {
        showLoadingDialog();
        String phoneNum = binding.etInputPhone.getText().toString().trim();
        String code = binding.etInputCode.getText().toString().trim();
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put("phone", phoneNum);
            requestDate.put("captcha", code);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().loginByCode(requestBody), new MyObserver<HttpRespond<UserInfoModel>>() {
            @Override
            protected void onSuccess(HttpRespond<UserInfoModel> userInfoModelHttpRespond) {
                dismissLoadingDialog();
                if (Constant.SUCCESS == userInfoModelHttpRespond.code) {
                    SPUtil.put(Constant.phoneNum, phoneNum);
                    UserInfoModel userInfoModel = userInfoModelHttpRespond.data;
                    if (null != userInfoModel) {
                        MyApplication.manager.saveUserInfo(userInfoModelHttpRespond.data);
                        if (null == userInfoModel.getDataVisualRegion()) {
                            ToastHelper.show(getString(R.string.contact_rd_department));
                        } else {
                            Constant.isLogout = false;
                            JumpIntent.jump(LoginActivity.this, MainActivity.class, true);
                        }
                    }
                } else {
                    ToastHelper.show(userInfoModelHttpRespond.msg);
                }
            }

            @Override
            protected void onFail(Throwable e) {
                dismissLoadingDialog();
                ToastHelper.show(e.getMessage());
            }
        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        changeBtnStatus();
    }

    private void changeBtnStatus() {
        if (!TextUtils.isEmpty(binding.etInputPhone.getText()) && !TextUtils.isEmpty(binding.etInputCode.getText())) {
            binding.btnConfirm.setEnabled(true);
            binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_sel);
        } else {
            binding.btnConfirm.setEnabled(false);
            binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_def);
        }
    }
}